package com.ycfmedical.bed;


import com.bilibili.magicasakura.utils.ThemeUtils;
import com.facebook.stetho.Stetho;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.TIMGroupReceiveMessageOpt;
import com.tencent.TIMLogLevel;
import com.tencent.TIMManager;
import com.tencent.qalsdk.sdk.MsfSdkUtils;
import com.ycfmedical.bed.business.InitBusiness;
import com.ycfmedical.bed.business.TlsBusiness;
import com.ycfmedical.bed.utils.Foreground;
import com.ycfmedical.bed.utils.ThemeHelper;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;


/**
 * 全局Application
 */
public class bBcApplication extends MultiDexApplication implements ThemeUtils.switchColor{

    private static Application sContext;
    private RefWatcher mRefWatcher;//leakCanary观察器

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sContext = this;

        _initDeviceMetrics();
        _initImSDK();
        _initImPush();
        ThemeUtils.setSwitchColor(this);

        installLeakCanary();//leakCanary内存泄露检查
        //Debug包 用于调试Retrofit网络请求
        if (BuildConfig.DEBUG) {
            Stetho.initializeWithDefaults(sContext);
        }

    }

    private void _initDeviceMetrics() {
        Constants.screenWidth = sContext.getResources().getDisplayMetrics().widthPixels;
        Constants.screenHeight = sContext.getResources().getDisplayMetrics().heightPixels;
        Constants.density = sContext.getResources().getDisplayMetrics().density;
    }


    private void _initImSDK() {
        // 设置IMSDK 内部Log等级
        SharedPreferences pref = getSharedPreferences(Constants.SHARE_IM_KEY, MODE_PRIVATE);
        int loglvl = pref.getInt("loglvl", TIMLogLevel.ERROR.ordinal());
        InitBusiness.start(getApplicationContext(),loglvl);//初始化IMSDK
        TlsBusiness.init(getApplicationContext());//初始化TLS腾讯后台
    }


    private void _initImPush() {

        Foreground.init(this);
        if (MsfSdkUtils.isMainProcess(this))
        {
            TIMManager.getInstance().setOfflinePushListener((mTIMOfflinePushNotification) -> {

                if (mTIMOfflinePushNotification.getGroupReceiveMsgOpt() == TIMGroupReceiveMessageOpt.ReceiveAndNotify)
                {
                    // 消息被设置为需要提醒
                    mTIMOfflinePushNotification.doNotify(getApplicationContext(), R.mipmap.ic_launcher);
                }
            });
        }

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        this.mRefWatcher = null;
    }

    /**
     * 安装leakCanary检测内存泄露
     */
    protected void installLeakCanary() {
        this.mRefWatcher = BuildConfig.USE_CANARY ? LeakCanary.install(this) : RefWatcher.DISABLED;
    }

    /**
     * 获得leakCanary观察器
     *
     * @param context
     * @return
     */
    public static RefWatcher getRefWatcher(Context context) {
        bBcApplication application = (bBcApplication) context.getApplicationContext();
        return application.mRefWatcher;
    }

    public static Context getContext() {
        return sContext;
    }


    @Override
    public int replaceColorById(Context context, @ColorRes int colorId) {
        if (ThemeHelper.isDefaultTheme(context)) {
            return context.getResources().getColor(colorId);
        }
        String theme = _getTheme(context);
        if (theme != null) {
            colorId = _getThemeColorId(context, colorId, theme);
        }
        return context.getResources().getColor(colorId);
    }

    @Override
    public int replaceColor(Context context, @ColorInt int originColor) {
        if (ThemeHelper.isDefaultTheme(context)) {
            return originColor;
        }
        String theme = _getTheme(context);
        int colorId = -1;

        if (theme != null) {
            colorId = _getThemeColor(context, originColor, theme);
        }
        return colorId != -1 ? getResources().getColor(colorId) : originColor;
    }

    private String _getTheme(Context context) {
        if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_STORM) {
            return "blue";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_HOPE) {
            return "purple";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_WOOD) {
            return "green";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_LIGHT) {
            return "green_light";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_THUNDER) {
            return "yellow";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_SAND) {
            return "orange";
        } else if (ThemeHelper.getTheme(context) == ThemeHelper.CARD_FIREY) {
            return "red";
        }
        return null;
    }

    private
    @ColorRes
    int _getThemeColorId(Context context, int colorId, String theme) {
        switch (colorId) {
            case R.color.theme_color_primary:
                return context.getResources().getIdentifier(theme, "color", getPackageName());
            case R.color.theme_color_primary_dark:
                return context.getResources().getIdentifier(theme + "_dark", "color", getPackageName());
            case R.color.theme_color_primary_trans:
                return context.getResources().getIdentifier(theme + "_trans", "color", getPackageName());
        }
        return colorId;
    }

    private
    @ColorRes
    int _getThemeColor(Context context, int color, String theme) {
        switch (color) {
            case 0xfffb7299:
                return context.getResources().getIdentifier(theme, "color", getPackageName());
            case 0xffb85671:
                return context.getResources().getIdentifier(theme + "_dark", "color", getPackageName());
            case 0x99f0486c:
                return context.getResources().getIdentifier(theme + "_trans", "color", getPackageName());
        }
        return -1;
    }
}